package com.example.EatOnTrojans;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;



import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class Result extends Activity {
	
	private static final int final_int_id=1;
	private ArrayList<RestRecord> rest_info = new ArrayList<RestRecord>();
	private ArrayList<RestRecord> restaurantList = new ArrayList<RestRecord>();
	private ImageView logoBanner1;
	private ListView listView;
	String detial;
	private ProgressDialog progressDialog;
	/** Called when the activity is first created. */
    @SuppressWarnings("static-access")
	@Override
    public void onCreate(Bundle savedInstanceState) {
    	/*
    	try {
			Thread.currentThread().sleep(5000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		*/
        super.onCreate(savedInstanceState);
        setContentView(R.layout.result);
        
        logoBanner1 = (ImageView) findViewById(R.id.banner1);
        
        logoBanner1.setOnClickListener(new OnClickListener(){
        	public void onClick(View v){
        		
        		Bundle data = new Bundle();
                Intent intent = new Intent(Result.this,EatOnTrojansActivity.class);
                intent.putExtras(data);
                startActivity(intent);
        	}
        });
        
        Intent intent = getIntent();
		Bundle b = intent.getExtras();
		String rName = b.getString("restName");
		String rType = b.getString("restType");
        System.out.println(rName);
		
		listView=(ListView)findViewById(R.id.listView1);
		
		//InputStream is=this.getClass().getResourceAsStream("restaurant.xml");
		InputStream in = GoogleMapsActivity.class.getClassLoader().getResourceAsStream("restaurant.xml");
		if(in==null){
        	Toast.makeText(getApplicationContext(), "Input stream is null",Toast.LENGTH_SHORT).show();
        }else{
	        DomXMLReader reader = new DomXMLReader();
	        try {
	        	restaurantList = reader.readXML(in);
			} catch (ParserConfigurationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SAXException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			restaurantList.get(0).image=R.drawable.rc_retail_tutor;
			restaurantList.get(1).image=R.drawable.irc;
			restaurantList.get(2).image=R.drawable.rc_retail_shop;
			restaurantList.get(3).image=R.drawable.rc_cc_panda;
			restaurantList.get(4).image=R.drawable.rc_cc_wahoos;
			restaurantList.get(5).image=R.drawable.rc_cc_carls;
			restaurantList.get(6).image=R.drawable.rc_cc_cpk;
			restaurantList.get(7).image=R.drawable.rc_cc_seeds;
			restaurantList.get(8).image=R.drawable.rc_retail_tgrounds;
			restaurantList.get(9).image=R.drawable.rc_retail_coffeebean;
			restaurantList.get(10).image=R.drawable.cafe84;
			
			boolean hasResult=false;
			if(rName!=null){
				System.out.println("name not null");
				for(RestRecord restaurant : restaurantList){
					if(rName.equals(restaurant.name)){
						System.out.println(restaurant.name);
						rest_info.add(restaurant);
						hasResult=true;
					}
				}
			}
			
			if(rType!=null){
				for(RestRecord restaurant : restaurantList){
					if(rType.equals(restaurant.type)){
						rest_info.add(restaurant);
						hasResult=true;
					}
				}
				if(!hasResult){
					for(RestRecord restaurant : restaurantList){
						if(rType.equals(restaurant.cuisine)){
							rest_info.add(restaurant);
							hasResult=true;
						}
					}
				}
			}
		
			if(hasResult){
				
				//assign values to the restaurants to be shown in list view
				
				listView.setAdapter(new RestItemAdapter(this, android.R.layout.simple_list_item_1, rest_info));
				listView.setOnItemClickListener(new OnItemClickListener() {
					public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3) {
						Bundle bd=new Bundle();
						bd.putInt("position", position);
						showDialog(final_int_id, bd);
					}
				});
				
			}
			else{
				Toast.makeText(getApplicationContext(), "No Result! Please enter the correct NAME!",Toast.LENGTH_SHORT).show();
	    		
			}
			
		}
    }
    
    public class RestItemAdapter extends ArrayAdapter<RestRecord> {
		private ArrayList<RestRecord> restaurant;

		public RestItemAdapter(Context context, int textViewResourceId, ArrayList<RestRecord> restaurants) {
			super(context, textViewResourceId, restaurants);
			this.restaurant = restaurants;
		}

		@Override
		public View getView(int position, View displayresult, ViewGroup parent) {
			View showresult = displayresult;
			if (showresult == null) {
				LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				showresult = vi.inflate(R.layout.listview, null);
			}
			
			RestRecord rest = restaurant.get(position);
			if (rest != null) {
				ImageView restImg = (ImageView) showresult.findViewById(R.id.resultImage);
				TextView restNam = (TextView) showresult.findViewById(R.id.restName);
				TextView restTyp = (TextView) showresult.findViewById(R.id.restType);
				TextView openHr = (TextView) showresult.findViewById(R.id.openTime);
				TextView mil = (TextView) showresult.findViewById(R.id.miles);

				restNam.setText(rest.name);
				restTyp.setText(rest.type);
				openHr.setText(rest.openHour);
				mil.setText(rest.mile+" miles");
				//Bitmap bm = getBitmap(rest.imageURL);
				//restImg.setImageBitmap(bm);
				restImg.setImageResource(rest.image);
				
				
				
			}
			return showresult;
		}
	}
    
	 @Override
	 protected Dialog onCreateDialog(final int id){
		 switch(id){
		 case final_int_id:
		 Context c=this;
		 Dialog d=new Dialog(c);
		 d.requestWindowFeature(Window.FEATURE_NO_TITLE);
		 return d;
		 
		 default:return super.onCreateDialog(id);
		 }  
	 }
	 
	 protected void onPrepareDialog(final int id, final Dialog dialog, Bundle b) {
		 switch (id) {
		 case final_int_id:
			
			  dialog.setContentView(R.layout.dialog);
			  dialog.setCancelable(false);
			  int position = b.getInt("position");
			  RestRecord diagRest = rest_info.get(position);
			  
			  TextView diagRestNam = (TextView) dialog.findViewById(R.id.diagName);
			  ImageView cancel = (ImageView) dialog.findViewById(R.id.cancel);
			  TextView diagRestLoc = (TextView) dialog.findViewById(R.id.diagLoc);
			  TextView textView5 = (TextView) dialog.findViewById(R.id.diagHour);
			  ImageView diagImage = (ImageView) dialog.findViewById(R.id.diagImg);
			  TextView diagReview = (TextView) dialog.findViewById(R.id.diagRev);
			  TextView diagRate = (TextView) dialog.findViewById(R.id.diagRate);
			  RatingBar diagRateBar = (RatingBar)dialog.findViewById(R.id.diagStar);
			  Button diagButton = (Button)dialog.findViewById(R.id.diagBut);
			  
			  diagRestNam.setText(diagRest.name);
			  //Bitmap bm = getBitmap(diagRest.imageURL);
			  //diagImage.setImageBitmap(bm);
			  diagImage.setImageResource(diagRest.image);
			  diagRestLoc.setText("Location: "+diagRest.location);
			  textView5.setText("Hour: "+diagRest.openHour);
			  diagReview.setText(diagRest.type+": "+diagRest.cuisine);
			  diagRate.setText(diagRest.menu);
			  diagRateBar.setRating(diagRest.rate);
			  diagButton.setText("Route");
			  detial=diagRest.name+";"+diagRest.location+";"+diagRest.type+";"+diagRest.cuisine+";"+diagRest.openHour+";"+diagRest.menu+";"+diagRest.imageURL+";"+diagRest.rate+";"+diagRest.latitude+";"+diagRest.longitude;
			  
			  
			  cancel.setOnClickListener(new OnClickListener(){
		        	public void onClick(View v){
		        		dialog.dismiss();
		        	}
		        });
			  
			  diagButton.setOnClickListener(new OnClickListener(){
		        	public void onClick(View v){
		        		progressDialog = new ProgressDialog(Result.this);
	            		progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
	            		progressDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
	            		progressDialog.setMessage("Calculating...");
	            		
	            		progressDialog.show();  
	    				Intent intent = new Intent();
	        			intent.setClass(Result.this, RouteMapsActivity.class);
	        			Bundle bundle = new Bundle();
	        			bundle.putString("detial", detial);
	        			intent.putExtras(bundle);
	        			Result.this.startActivity(intent);
		        	}
		        });
			  break;
		 }
	 }
	 
	 
	 public Bitmap getBitmap(String imageURL){ 
	 		//initialize bitmap
	 		Bitmap mBitmap = null; 
	 		try { 
	 			//open connection to the URL
	 			URL url = new URL(imageURL); 
	 			URLConnection conn = url.openConnection(); 
	 			conn.connect();
	 			InputStream is = conn.getInputStream(); 
	 			BufferedInputStream buff = new BufferedInputStream(is);
	 			//get image stream
	 			mBitmap = BitmapFactory.decodeStream(buff); 
	 			buff.close();
	 			is.close();
	 		} catch (MalformedURLException e) { 
	 			e.printStackTrace(); 
	 		} catch (IOException e) { 
	 			e.printStackTrace(); 
	 		} 
	 		return mBitmap; 
	 	} 
}

